const { defineConfig } = require('@vue/cli-service')
const webpack = require('webpack')
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
const fs = require('fs')
// const  CopyPlugin = require('copy-webpack-plugin')
const path = require("path")
const package = require('./package.json')
const timestamp = new Date().getTime()
const version = package.version

function resolve(dir) {
  return path.join(__dirname, dir)
}

// 移动systemjs至publish目录
// fs.copyFile(
//   path.resolve(__dirname, './node_modules/systemjs/dist/system.min.js'),
//   path.resolve(__dirname, './public/system.min.js'),
//   function(){}
// )

const isProd = process.env.NODE_ENV === 'production'
let target = process.env.npm_lifecycle_event
const isLib = target === 'designer' || target === 'drender'

module.exports = defineConfig({
  pages: {
    index: {
      entry: isProd ? 'src/loader.js' : 'src/main.js',
      template: 'public/index.html',
      filename: 'index.html',
      inject: true
    },
    main: {
      entry: 'src/main.js',
      template: 'public/index.html',
      filename: 'main.html',
      inject: true
    },
    'micro-app': {
      entry: 'src/micro-app.js',
      template: 'public/index.html',
      filename: 'micro-app.html',
      inject: true
    }
  },
  outputDir: !isLib ? '../dist/app' : '../dist/' + (target === 'drender' ? 'designer/drender' : target) + '/dist',
  transpileDependencies: true,
  runtimeCompiler: true,
  // baseUrl: process.env.NODE_ENV === 'production' ? './' : '/',
  publicPath: isProd ? '/df3s/tigerlair/app/' : '/',
  assetsDir: 'static',
  productionSourceMap: false,
  filenameHashing: false, // 取消hash
  // css: {
  //   // 将组件内部的css提取到一个单独的css文件（只用在生产环境）
  //   // 也可以是传递给 extract-text-webpack-plugin 的选项对象
  //   extract: true, // 允许生成 CSS source maps?
  //   sourceMap: false, // pass custom options to pre-processor loaders. e.g. to pass options to // sass-loader, use { sass: { ... } }
  //   loaderOptions: {}, // Enable CSS modules for all css / pre-processor files. // This option does not affect *.vue files.
  //   modules: false
  // },
  chainWebpack: config => {
    config.resolve.alias
      .set("@", resolve("src"))
      .set("@assets", resolve("src/assets"))
      .set("@vendor", resolve("src/assets/vendor"))
      .set("@components", resolve("src/components"))
    isLib && config.plugin('chunkPlugin').use(webpack.optimize.LimitChunkCountPlugin, [{
      maxChunks: 1 // 此处设置文件数量
    }])
    config.module.rule('css');
    // .exclude
    // .add('node-modules/blubb')
    // .end();
  },
  configureWebpack: (config) => {
    const isAnalyzeMode = false
    if (isProd && isAnalyzeMode) {
      config.plugins.push(
        new BundleAnalyzerPlugin({
          // 生成静态文件
          analyzerMode: 'static',
        })
      )
    }
    const packageName = 'tigerlair'
    return {
      plugins: [
        // new CopyPlugin({
        //   patterns: [
        //     {
        //       from: path.resolve(__dirname, './src'),
        //       to: 'dist'
        //     }
        //   ]
        // })
      ],
      output: {
        libraryTarget: 'umd',
        library: packageName,
        // filename: `[name].${version}.${timestamp}.js`,
        // chunkFilename: `[name].${version}.${timestamp}.js`
      },
      externals: isProd ? [
        {
          'vue-router': 'vue-router',
          'vuex': 'vuex',
          'system': 'system',
          'axios': 'axios',
          'iview': 'iview',
          'moment': 'moment',
          'echarts': 'echarts',
          'element-ui': 'element-ui'
        },
        !isLib ? /^@daelui\/dogjs/ : /^@daelui/,
        !isLib ? function(context, request, callback) {
          if (/vendor\/monaco-editor$|vendor\/(vue-)?quill|vendor\/highlightjs/.test(request)) {
            return callback(null, request.replace(/.*vendor\//, ''))
          }
          callback()
        }: '',
        function(context, request, callback) {
          if (/^@daelui\/dogui\/dist|element-ui\/lib\/theme/.test(request)) {
            return callback(null, request)
          }
          callback()
        }
      ] : {},
      // optimization: {
      //   splitChunks: {
      //     chunks: 'all',
      //     cacheGroups: {
      //       //公用模块抽离
      //       common: {
      //         chunks: 'initial',
      //         minSize: 0, //大于0个字节
      //         minChunks: 2, //抽离公共代码时，这个代码块最小被引用的次数
      //       },
      //       //第三方库抽离
      //       vendor: {
      //         priority: 1, //权重
      //         test: /node_modules/,
      //         chunks: 'initial',
      //         minSize: 0, //大于0个字节
      //         minChunks: 2, //在分割之前，这个代码块最小应该被引用的次数
      //       },
      //     }
      //   }
      // }
    }
  }
})
